from django.shortcuts import render, redirect
from django.views.decorators.csrf import csrf_exempt
from django.http import JsonResponse
from service.tools import Tools
from vote.form import VoteForm, CreateVote, CreateVoteOption
from vote.models import Vote


def index(request):
    return render(request, 'vote/index.html', locals())


@csrf_exempt
def new(request):
    title = '发起投票-社区-量子企业数据智能分析系统-专注企业加速'
    if request.method == "POST":
        vote = CreateVote(request.POST)
        if vote.is_valid():
            id = vote.save().pk
            return redirect('/vote/step2/' + str(id))
        else:
            message = Tools.format_errors('bbs', vote.errors)
            return render(request, 'vote/new.html', locals())
    else:
        vote = VoteForm(request.POST)
        return render(request, 'vote/new.html', locals())


@csrf_exempt
def step2(request, id):
    title = '发起投票-社区-量子企业数据智能分析系统-专注企业加速'
    vote = Vote.objects.filter(pk=id)[0]
    vote_options = vote.voteoption_set.all()
    return render(request, 'vote/step2.html', locals())


@csrf_exempt
def add_vote_option(request):
    vote_option = CreateVoteOption(request.POST)
    if vote_option.is_valid():
        vp = vote_option.save()
        return render(request, 'vote/_vote_option.html', locals())
    else:
        return JsonResponse({'msg': 'true', 'errors': Tools.format_errors(vote_option.errors)})


def show(request, id):
    vote = Vote.objects.filter(pk=id)[0]
    vote_option = vote.voteoption_set.all()
    return render(request, 'vote/show.html', locals())